package org.cshoo.sys.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.ResultEvent;
	import mx.controls.Tree;
	
	import org.cshoo.common.util.MessageUtil;
	import org.cshoo.sys.business.OrganizationDelegate;
	import org.cshoo.sys.event.AddOrganizationEvent;
	import org.cshoo.sys.model.SysModelLocator;
	import org.cshoo.sys.model.vo.Organization;
	
	public class AddOrganizationCommand implements ICommand, IResponder
	{
		private　var　_model:SysModelLocator　=　SysModelLocator.getInstance();
		
		private var parent:Organization;
		
		private var organizationTree:Tree;
		
		public function execute(event:CairngormEvent):void
		{
			var organization:Organization = (event as AddOrganizationEvent).organization;
			parent = organization.parent;
			organizationTree = (event as AddOrganizationEvent).organizationTree;
			var organizationDelegate:OrganizationDelegate = new OrganizationDelegate(this);
			organizationDelegate.addOrganization(organization);
		}
		
		public function result(event:Object):void
		{
			var organization:Organization = (event as ResultEvent).result as Organization;
			organization.parent = parent;
			
			if(organization.parent != null)
			{
				if((organization.order - 1) < parent.children.length)
				{
					organizationTree.dataDescriptor.addChildAt(parent,organization,organization.order - 1);
					organizationTree.expandItem(parent,true);
				}
				else
				{
					organizationTree.dataDescriptor.addChildAt(parent,organization,parent.children.length);
					organizationTree.expandItem(parent,true);
				}
			}
			else
			{
				if((organization.order - 1) < _model.rootOrganizationCollection.length)
					_model.rootOrganizationCollection.addItemAt(organization,organization.order - 1);
				else
					_model.rootOrganizationCollection.addItemAt(organization,_model.rootOrganizationCollection.length);
			}
			MessageUtil.showInfoMessage("组织机构数据添加成功");
			
		}
		
		public function fault(info:Object):void
		{
			Alert.show("服务器端已经停止");
		}
	}
}